<template>
	<div id="app">
		<section class="todoapp">
			<header class="header">
				<h1>Todos</h1>
				<input
					class="new-todo"
					autofocus=""
					autocomplete="off"
					placeholder="What needs to be done?"
					v-model="title"
					@keyup.enter="handleInput"
				/>
			</header>
			<section class="main" v-show="todoList.length > 0">
				<input
					id="toggle-all"
					class="toggle-all"
					type="checkbox"
					v-model="isAllDone"
				/>
				<label for="toggle-all">Mark all as complete</label>
				<transition-group class="todo-list" name="todo" tag="ul">
					<li
						v-for="item in filteredList"
						:key="item.id"
						class="todo"
						:class="{ completed: item.isFinish, editing: item === editingTodo }"
					>
						<div class="view">
							<input class="toggle" type="checkbox" v-model="item.isFinish" />
							<label @dblclick="handleEdit(item)">{{ item.title }}</label>
							<button class="destroy" @click="handleDelete(item)"></button>
						</div>
						<input
							class="edit"
							type="text"
							v-model.lazy="tempContent"
							@mouseenter="handleAutoFocus($event.target)"
							@blur="handleDoneEdit(item)"
							@keyup.enter="handleDoneEdit(item)"
							@keyup.esc="handleCancelEdit(item)"
						/>
					</li>
				</transition-group>
			</section>
			<footer class="footer" v-show="todoList.length > 0">
				<span class="todo-count">
					<strong>{{ activeList.length }}</strong>
					<span>item{{ activeList.length == 1 ? "" : "s" }} todo</span>
				</span>
				<ul class="filters">
					<li>
						<a href="#/all" :class="{ selected: category === 'all' }">All</a>
					</li>
					<li>
						<a href="#/active" :class="{ selected: category === 'active' }"
							>Active</a
						>
					</li>
					<li>
						<a
							href="#/completed"
							:class="{ selected: category === 'completed' }"
							>Completed</a
						>
					</li>
				</ul>
				<button
					class="clear-completed"
					@click="handleClearCompleted"
					v-show="completedList.length >= 1"
				>
					Clear completed
				</button>
			</footer>
		</section>
	</div>
</template>

<script>
import {
	getTodoList,
	saveTodoList,
	deleteTodo,
	addTodo,
	generateId,
} from "./utils/todosStorage.js";

export default {
	name: "App",
	data() {
		return {
			// 输入的内容，默认为 ""
			title: "",
			// 类别，默认为 all
			category: "all",
			// todo 列表
			todoList: [],
			// 正在编辑的 todo
			editingTodo: null,
			// 正在编辑的 todo 的内容
			tempContent: "",
		};
	},
	methods: {
		handleInput() {
			this.title = this.title.trim();
			if (this.title === "") {
				// 如果没有输入内容，则什么都不做
				return;
			}
			let todoItem = {
				id: generateId(),
				title: this.title,
				isFinish: false,
			};
			// 添加到 todoList
			addTodo(todoItem, this.todoList);
			// 清空输入框
			this.title = "";
		},
		handleHashChange() {
			// 切换类别
			let hash = location.hash.replace(/#\/?/, "");
			this.category = hash;
		},
		handleClearCompleted() {
			// 清空已完成的 todo
			this.todoList = this.activeList;
		},
		handleDelete(todoItem) {
			// 删除指定的 todo
			this.todoList = this.todoList.filter((item) => item.id !== todoItem.id);
		},
		handleEdit(todoItem) {
			this.tempContent = todoItem.title;
			this.editingTodo = todoItem;
		},
		handleAutoFocus(dom) {
			// 由于鼠标双击出现的编辑框没有自动出现焦点，所以需要手动聚焦
			dom.focus();
		},
		handleDoneEdit(todoItem) {
			// 编辑完成
			if (this.tempContent.trim() === "") {
				//如果没有里面已经没有内容了，则删除
				this.handleDelete(todoItem);
			}
			todoItem.title = this.tempContent;
			this.editingTodo = null;
		},
		handleCancelEdit() {
			// 取消编辑
			this.editingTodo = null;
		},
	},
	computed: {
		filteredList() {
			// 这是根据 category 的值过滤 todoList 后的列表
			if (this.category === "active") {
				// 如果是 active，返回未完成的 todo
				return this.activeList;
			} else if (this.category === "completed") {
				// 如果是 completed，返回已完成的 todo
				return this.completedList;
			} else {
				// 如果是 all 或者其它情况则默认返回全部
				// 将数组原地排序，使得已完成的放在后面
				this.todoList.sort((f, l) => f.isFinish - l.isFinish);
				return this.todoList;
			}
		},
		activeList() {
			// 未完成的 todo
			return this.todoList.filter((item) => !item.isFinish);
		},
		completedList() {
			// 未完成的 todo
			return this.todoList.filter((item) => item.isFinish);
		},
		isAllDone: {
			// 给 checkbox 复选框绑定一个计算属性
			get() {
				return this.activeList.length === 0;
			},
			set(value) {
				this.todoList.forEach((item) => {
					item.isFinish = value;
				});
			},
		},
	},
	watch: {
		todoList: {
			handler(newVal, oldVal) {
				// 每当todoList有改动时，保存到本地
				console.log("todoList改动");
				saveTodoList(newVal);
			},
			// 进行深度监听，监听所有属性
			deep: true,
		},
	},

	created() {
		// 对数据初始化
		this.todoList = getTodoList();
		// 监听 hash 值的变化
		window.addEventListener("hashchange", this.handleHashChange);
	},
	beforeDestroy() {
		// 移除监听
		window.removeEventListener("hashchange", this.handleHashChange);
	},
};
</script>

<style scoped>
.todo-enter-active,
.todo-leave-active,
.todo-move {
	transition: all 1s;
}
.todo-enter {
	opacity: 0;
	transform: translateY(100%);
}
.todo-leave-to {
	opacity: 0;
	transform: translateX(50%);
}
.todo-leave-active {
	position: absolute !important;
}
</style>
